AddressSelector.vue 10.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
<template>
  <view>
    <!-- 地址选择弹窗 -->
    <nut-popup
      :visible="visible"
      position="bottom"
      :style="{ height: '85%' }"
      close-icon-position="top-right"
      @close="closeModal"
    >
      <view class="address-modal">
        <view class="address-modal-header">
          <text class="address-modal-title">选择地址</text>
        </view>

        <view class="address-modal-content">
          <!-- 省市县选择 -->
          <view class="address-section">
            <text class="address-section-title">选择省市县</text>
            <view
              class="area-selector"
              @click="showAreaPicker = true"
            >
              <text class="area-text" :class="{ 'area-selected': selectedAreaText }">
                {{ selectedAreaText || '请选择省市县' }}
              </text>
              <ArrowRight color="#9ca3af" size="12" />
            </view>
          </view>

          <!-- 详细地址输入 -->
          <view class="address-section">
            <text class="address-section-title">详细地址</text>
            <nut-textarea
              v-model="detailAddress"
              placeholder="请输入详细地址(街道、门牌号等)"
              rows="3"
              class="detail-address-input"
              :cursorSpacing="50"
            />
          </view>
        </view>

        <view class="address-modal-footer">
          <nut-button
            type="primary"
            color="orange"
            block
            @click="confirmAddress"
            :disabled="!selectedAreaText || !detailAddress.trim()"
          >
            确定
          </nut-button>
        </view>
      </view>
    </nut-popup>

    <!-- 省市县级联选择器 - 放在popup外面避免层级冲突 -->
    <nut-config-provider :theme-vars="themeVars">
      <nut-cascader
        v-model="selectedAreaCodes"
        v-model:visible="showAreaPicker"
        :options="areaData"
        @change="onAreaChange"
        @path-change="onAreaPathChange"
        title="请选择省市县"
      />
    </nut-config-provider>
  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { RectRight, ArrowRight } from '@nutui/icons-vue-taro'
import { areaList } from '@vant/area-data'

const themeVars = {
    // cascaderBarColor: 'orange',
    // cascaderItemColor: 'orange',
    cascaderItemActiveColor: 'orange',
}

/**
 * 转换@vant/area-data的扁平化数据为NutUI Cascader组件需要的树形结构
 * @param {Object} areaList - @vant/area-data的原始数据
 * @returns {Array} - 转换后的树形数据格式
 */
const transformAreaData = (areaList) => {
  const { province_list, city_list, county_list } = areaList

  return Object.keys(province_list).map(provinceCode => {
    const provinceName = province_list[provinceCode]

    // 获取该省份下的所有城市
    const cities = Object.keys(city_list)
      .filter(cityCode => cityCode.startsWith(provinceCode.substring(0, 2)))
      .map(cityCode => {
        const cityName = city_list[cityCode]

        // 获取该城市下的所有区县
        const counties = Object.keys(county_list)
          .filter(countyCode => countyCode.startsWith(cityCode.substring(0, 4)))
          .map(countyCode => ({
            value: countyCode,
            text: county_list[countyCode]
          }))

        return {
          value: cityCode,
          text: cityName,
          children: counties.length > 0 ? counties : undefined
        }
      })

    return {
      value: provinceCode,
      text: provinceName,
      children: cities.length > 0 ? cities : undefined
    }
  })
}

/**
 * 组件属性定义
 */
const props = defineProps({
  // 当前选中的地址信息
  modelValue: {
    type: Object,
    default: () => ({
      province: '',
      city: '',
      county: '',
      province_code: '',
      city_code: '',
      county_code: '',
      detail_address: '',
      full_address: ''
    })
  },
  // 占位符文本
  placeholder: {
    type: String,
    default: '请选择省市县并填写详细地址'
  },
  // 控制弹窗显示状态
  visible: {
    type: Boolean,
    default: false
  }
})

/**
 * 组件事件定义
 */
const emit = defineEmits(['update:modelValue', 'change', 'update:visible'])

/**
 * 地址选择相关状态
 */
const showAreaPicker = ref(false)
const selectedAreaCodes = ref([])
const selectedAreaText = ref('')
const detailAddress = ref('')
const areaData = ref(transformAreaData(areaList))

/**
 * 计算完整地址
 */
const fullAddress = computed(() => {
  if (selectedAreaText.value && detailAddress.value.trim()) {
    return `${selectedAreaText.value} ${detailAddress.value.trim()}`
  }
  return ''
})

/**
 * 初始化地址数据
 * @param {Object} addressData - 地址数据对象
 */
const initAddressData = (addressData) => {
  // 统一设置详细地址
  detailAddress.value = addressData.detail_address || addressData.idcard_address || ''

  // 优先使用code值来设置级联选择器的选中状态
  if (addressData.province_code && addressData.city_code && addressData.county_code) {
    selectedAreaCodes.value = [
      addressData.province_code,
      addressData.city_code,
      addressData.county_code
    ]
    // 根据code值直接从扁平化数据中获取对应的文本
    const { province_list, city_list, county_list } = areaList
    const provinceName = province_list[addressData.province_code] || ''
    const cityName = city_list[addressData.city_code] || ''
    const countyName = county_list[addressData.county_code] || ''

    if (provinceName && cityName && countyName) {
      selectedAreaText.value = `${provinceName}${cityName}${countyName}`
    }
  } else if (addressData.province && addressData.city && addressData.county) {
    // 兼容旧的文本格式
    selectedAreaText.value = `${addressData.province}${addressData.city}${addressData.county}`
  } else {
    selectedAreaText.value = ''
    selectedAreaCodes.value = []
  }
}

/**
 * 监听props变化,初始化组件数据
 */
watch(() => props.modelValue, (newValue) => {
  if (newValue) {
    initAddressData(newValue)
  }
}, { immediate: true, deep: true })

/**
 * 地区选择变化回调(选中值改变时触发)
 * @param {Array} value - 选中的值数组
 * @param {Array} pathNodes - 选中的路径节点数组
 */
const onAreaChange = (value, pathNodes) => {
  if (pathNodes && Array.isArray(pathNodes) && pathNodes.length === 3) {
    selectedAreaCodes.value = value
    selectedAreaText.value = pathNodes
      .filter(node => node && node.text)
      .map(node => node.text)
      .join('')
    // 选择完三级地址后自动关闭选择器
    showAreaPicker.value = false
  }
}

/**
 * 地区路径选择变化回调(选中项改变时触发)
 * @param {Array} pathNodes - 选中的路径节点数组
 */
const onAreaPathChange = (pathNodes) => {
  if (pathNodes && Array.isArray(pathNodes)) {
    selectedAreaText.value = pathNodes
      .filter(node => node && node.text)
      .map(node => node.text)
      .join('')
  }
}



/**
 * 关闭地址选择弹窗
 */
const closeModal = () => {
  emit('update:visible', false)
}

/**
 * 确认地址选择
 */
const confirmAddress = () => {
  if (selectedAreaText.value && detailAddress.value.trim()) {
    const codes = selectedAreaCodes.value
    const areaText = getAreaTextFromCodes()
    const addressData = {
      ...areaText,
      province_code: codes[0] || '',
      city_code: codes[1] || '',
      county_code: codes[2] || '',
      detail_address: detailAddress.value.trim(),
      full_address: fullAddress.value
    }

    // 触发更新事件
    emit('update:modelValue', addressData)
    emit('change', addressData)

    // 关闭弹窗
    emit('update:visible', false)
  }
}

/**
 * 根据选中的codes获取地区文本信息
 * @returns {Object} - 包含省市县文本的对象
 */
const getAreaTextFromCodes = () => {
  const codes = selectedAreaCodes.value
  const { province_list, city_list, county_list } = areaList
  const result = { province: '', city: '', county: '' }

  if (codes.length >= 1 && province_list[codes[0]]) {
    result.province = province_list[codes[0]]
  }

  if (codes.length >= 2 && city_list[codes[1]]) {
    result.city = city_list[codes[1]]
  }

  if (codes.length >= 3 && county_list[codes[2]]) {
    result.county = county_list[codes[2]]
  }

  return result
}

// findNodeByCode 函数已移除,现在直接从 @vant/area-data 的扁平化数据中获取地区名称
</script>

<style lang="less">
// 地址选择器样式
.address-selector {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 32rpx;
  border: 1px solid #e5e7eb;
  border-radius: 24rpx;
  background-color: white;
  min-height: 96rpx;
  transition: all 0.2s ease;

  &:active {
    background-color: #f9fafb;
  }

  .address-text {
    font-size: 28rpx;
    color: #9ca3af;
    flex: 1;
    line-height: 1.6;
    word-break: break-all;

    &.address-selected {
      color: #111827;
    }
  }
}

// 地址选择弹窗样式
.address-modal {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: white;

  .address-modal-header {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 32rpx;
    border-bottom: 1px solid #f3f4f6;
    background-color: white;
    position: sticky;
    top: 0;
    z-index: 10;

    .address-modal-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #111827;
    }
  }

  .address-modal-content {
    flex: 1;
    padding: 32rpx;
    padding-bottom: 120rpx; // 为底部固定按钮预留空间
    overflow-y: auto;

    .address-section {
      margin-bottom: 48rpx;

      .address-section-title {
        display: block;
        font-size: 28rpx;
        font-weight: 500;
        color: #374151;
        margin-bottom: 24rpx;
      }

      .area-selector {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 24rpx 32rpx;
        border: 1px solid #e5e7eb;
        border-radius: 24rpx;
        background-color: white;
        transition: all 0.2s ease;

        &:active {
          background-color: #f9fafb;
        }

        .area-text {
          font-size: 28rpx;
          color: #9ca3af;
          flex: 1;
          line-height: 1.6;
          word-break: break-all;

          &.area-selected {
            color: #111827;
          }
        }
      }

      .detail-address-input {
        width: 100%;

        :deep(.nut-textarea) {
          border: 1px solid #e5e7eb;
          border-radius: 24rpx;

          .nut-textarea__textarea {
            padding: 24rpx 32rpx;
            font-size: 28rpx;
            line-height: 1.6;
            min-height: 160rpx;
          }
        }
      }
    }
  }

  .address-modal-footer {
    padding: 32rpx;
    border-top: 1px solid #f3f4f6;
    background-color: white;
    position: sticky;
    bottom: 0;
    z-index: 10;

    :deep(.nut-button) {
      border-radius: 24rpx;
      font-weight: 500;
      height: 88rpx;
    }
  }
}
</style>