SelectArea.js 6.18 KB
// components/SelectArea/SelectArea.js
// 直接使用 Vant 的 areaData 作为默认数据源
// const { areaList: vantAreaList } = require('@vant/area-data')

Component({
  options: {
    addGlobalClass: true
  },
  properties: {
    show: { type: Boolean, value: false },
    title: { type: String, value: '选择所在地区' },
    // 2 或 3,表示二级(省/市)或三级(省/市/区)
    columnsNum: { type: Number, value: 3 },
    value: { type: null, value: '' },
    areaList: { type: Object },
    confirmOnSelect: { type: Boolean, value: false }
  },
  data: {
    areaValues: [],
    currentValue: ''
  },
  observers: {
    // 当初始值、层级或数据源变化时,规范化初始值,并推导出 values
    'value, columnsNum, areaList': function (value, columnsNum, areaList) {
      let normalized = this.normalizeInitCode(value, columnsNum, areaList)
      if (!normalized) normalized = this.getDefaultCode(columnsNum, areaList)
      const values = this.mapValueToValues(normalized, columnsNum, areaList)
      this.setData({ currentValue: normalized, areaValues: values })
    }
  },
  methods: {
    // van-area 选项变化:保存当前 values
    onAreaChange(e) {
      const values = e && e.detail && e.detail.values ? e.detail.values : []
      this.setData({ areaValues: values })
    },
    // 外层 Popup 的“确定”按钮:输出当前选中结果
    onConfirm() {
      const { columnsNum, areaList, value } = this.properties
      const values = this.data.areaValues || []
      // 如未触发过 change,尝试根据初始 value 或默认值补齐 values
      let normalized = this.normalizeInitCode(value, columnsNum, areaList)
      if (!normalized) normalized = this.data.currentValue || this.getDefaultCode(columnsNum, areaList)
      const filledValues = values.length ? values : this.mapValueToValues(normalized, columnsNum, areaList)
      const codes = filledValues.map(v => v && v.code).filter(Boolean)
      const names = filledValues.map(v => v && v.name).filter(Boolean)
      const detail = {
        provinceCode: codes[0] || '',
        provinceName: names[0] || '',
        cityCode: codes[1] || '',
        cityName: names[1] || '',
        countyCode: columnsNum === 3 ? (codes[2] || '') : '',
        countyName: columnsNum === 3 ? (names[2] || '') : '',
        columnsNum,
        codes,
        names,
        text: names.join(' ')
      }
      this.triggerEvent('confirm', detail)
    },
    // 外层 Popup 的“取消”按钮(或遮罩关闭):透传取消
    onCancel() {
      this.triggerEvent('cancel')
    },
    // 规范化初始 code 为末级编码(兼容 2/3 级,支持省/市/区传入)
    normalizeInitCode(code = '', columnsNum = 3, areaList = {}) {
      if (!code) return ''
      const input = (code + '')
      const provCode = input.slice(0, 2) + '0000'
      const cityCode = input.slice(0, 4) + '00'
      if (columnsNum === 3) {
        // 已是区级
        if (input.length === 6 && input.slice(4) !== '00') return input
        // 传市级:找该市下第一个区
        if (areaList && areaList.county_list && !areaList.county_list[cityCode]) return cityCode // 当市下没有区级数据时 选中市级
        if (areaList && areaList.county_list) {
          const prefix = cityCode.slice(0, 4)
          const match = Object.keys(areaList.county_list).find(c => c.slice(0, 4) === prefix)
          if (match) return match
        }
        // 传省级:找该省下第一个市,再找该市下第一个区
        if (areaList && areaList.city_list) {
          const cMatch = Object.keys(areaList.city_list).find(c => c.slice(0, 2) === provCode.slice(0, 2))
          if (cMatch) {
            if (areaList && areaList.county_list) {
              const pfx = cMatch.slice(0, 4)
              const aMatch = Object.keys(areaList.county_list).find(c => c.slice(0, 4) === pfx)
              if (aMatch) return aMatch
            }
            return cMatch // 退化为市级
          }
        }
        return input // 无法推导则原样返回
      } else {
        // 二级:需要市级编码
        // 若传区级,转为市级
        if (input.length === 6 && input.slice(4) !== '00') return cityCode
        // 若传省级,选该省首个市
        if (areaList && areaList.city_list) {
          const cMatch = Object.keys(areaList.city_list).find(c => c.slice(0, 2) === provCode.slice(0, 2))
          if (cMatch) return cMatch
        }
        // 已是市级
        if (input.length === 6 && input.slice(4) === '00') return input
        return ''
      }
    },
    // 根据末级编码映射为 values 数组(兼容 2/3 级)
    mapValueToValues(code = '', columnsNum = 3, areaList = {}) {
      if (!code || !areaList || !areaList.province_list || !areaList.city_list) return []
      const provCode = (code + '').slice(0, 2) + '0000'
      const cityCode = (code + '').slice(0, 4) + '00'
      const values = []
      // 省
      const pName = areaList.province_list[provCode]
      if (pName) values.push({ code: provCode, name: pName })
      // 市
      const cName = areaList.city_list[cityCode]
      if (cName) values.push({ code: cityCode, name: cName })
      // 区
      if (columnsNum === 3) {
        const aName = (areaList.county_list || {})[code]
        if (aName) values.push({ code, name: aName })
      }
      return values
    },
    // 当无初始值时,基于数据源计算一个默认末级编码(保证有值)
    getDefaultCode(columnsNum = 3, areaList = {}) {
      const provinces = areaList && areaList.province_list ? Object.keys(areaList.province_list) : []
      if (!provinces.length) return ''
      const provCode = provinces.sort()[0]
      const cities = areaList && areaList.city_list ? Object.keys(areaList.city_list).filter(c => c.slice(0, 2) === provCode.slice(0, 2)) : []
      if (!cities.length) return ''
      const cityCode = cities.sort()[0]
      if (columnsNum === 2) return cityCode
      const counties = areaList && areaList.county_list ? Object.keys(areaList.county_list).filter(a => a.slice(0, 4) === cityCode.slice(0, 4)) : []
      if (!counties.length) return cityCode // 若无区,退化为市
      const countyCode = counties.sort()[0]
      return countyCode
    }
  }
})