index.vue 13.6 KB
<template>
  <div v-if="provinceView">
    <el-form ref="provinceForm" :model="provinceForm" :inline="inline" label-width="154px" >
      <el-form-item :label="provinceLabel" >
        <el-select size="small" v-model="provinceForm.provinceName" clearable placeholder="选择省份" @clear="selectProvince" class="select-padding" :style="{ width: subdistrict == 2 ? '52%' : '33.33%' }">
          <el-option v-for="(item, index) in AllData" :key="'province' + index" :label="item.name" :value="item.name" @click.native="selectProvince(item)"></el-option>
        </el-select>
        <el-select size="small" v-model="provinceForm.cityName" clearable placeholder="选择市" @clear="selectCity" class="select-padding" :style="{ width: subdistrict == 2 ? '52%' : '33.33%' }">
          <el-option v-for="(item, index) in cityList" :key="'city' + index" :label="item.name" :value="item.name" @click.native="selectCity(item)"></el-option>
        </el-select>
        <el-select v-if="subdistrict == 3" size="small" v-model="provinceForm.townName" clearable placeholder="选择区" @clear="selectTown" class="select-padding" :style="{ width: subdistrict == 2 ? '52%' : '33.33%' }">
          <el-option v-for="(item, index) in townList" :key="'town' + index" :label="item.name" :value="item.name" @click.native="selectTown(item)"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="detailAddressLabel" >
        <el-input size="small" v-if="mapView" readonly placeholder="请选择详细地址" v-model="provinceForm.fullAddress" class="map-input">
          <el-button size="small" slot="append" @click="hanleSelectMap" icon="el-icon-location-outline">
            <!-- <img src="@/assets/map.png" alt="" class="map-icon" /> -->
            <!-- <i class="gl-icon-location"></i> -->
          </el-button>
        </el-input>
      </el-form-item>
    </el-form>
    <GLDialog :visible.sync="dialogMapVisible" :mode="'big'" bigTitle="选择地址">
      <map-view ref="mapForm" :mapHeight="mapHeight"></map-view>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogMapVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="getAddress">确 定</el-button>
      </span>
    </GLDialog>
  </div>
</template>

<script>
import { baseConfig } from "@/main"
import mapView from './mapView.vue'
// import GLDialog from '@/packages/GLDialog/src/GLDialog'
export default {
  name: 'GLProvince',
  components: {
    mapView
    // GLDialog
  },
  props: {
    // 是否一行展示
    inline: {
      type: Boolean,
      default: false
    },
    // 省市级别,2--只显示省市,3--显示省市区
    subdistrict: {
      type: Number,
      //  `2-只显示省市`
      default: 2
    },
    // 组件是否展示,默认展示
    provinceView: {
      type: Boolean,
      default: true
    },
    // 地图组件是否展示,默认展示
    // 如果需要展示地图组件,需要下载vue-amap包,并且在main.js中引入
    // import VueAMap from "vue-amap"
    // Vue.use(VueAMap)
    // 初始化vue-amap
    // VueAMap.initAMapApiLoader({
    //     key: "bd290dc27d0945959280753215ddda71", // 这里写你申请的高德地图的key
    //     plugin: ["AMap.PlaceSearch", "AMap.Geocoder", "AMap.Geolocation"],
    //     v: "1.4.15"
    // });
    mapView: {
      type: Boolean,
      default: true
    },
    // 省份标签值
    provinceLabel: {
      type: String,
      default: '省市地址:'
    },
    // 详细地址标签值
    detailAddressLabel: {
      type: String,
      default: '详细地址:'
    }
  },
  data() {
    return {
      // 所有数据
      AllData: [],
      // 城市列表
      cityList: [],
      // 地区列表
      townList: [],
      provinceForm: {
        // 省份名称
        provinceName: '',
        // 城市名称
        cityName: '',
        // 地区名称
        townName: '',
        // 省份代码
        provinceCode: '',
        // 城市代码
        cityCode: '',
        // 地区代码
        townCode: '',
        lat: '',
        lng: '',
        // 全部地址
        fullAddress: ''
      },
      mapHeight: 380,
      dialogMapVisible: false,
      // 暂存地址表单
      addressData: {},
    }
  },
  mounted() {
    console.log(baseConfig, 'baseConfig---')
    if (this.provinceView) {
      this.provinceList()
    }
  },
  methods: {
    /*
     * @params:传入的为一个key-value的对象
     1、keywords --查询关键字,只支持单个关键词语搜索关键词支持:行政区名称、citycode、adcode
         列如:this.provinceList({keywords: '山东省'}),这样就可以筛选出山东省下的市、区信息
     2、subdistrict --设置显示下级行政区级数,0:不返回下级行政区;1:返回下一级行政区;2:返回下两级行政区;3:返回下三级行政区;
         不传的话默认为2,可以在组件中穿,也可以在调用方法的时候传,如果需要展示省市组件,传值最小为2
     3、page --最外层的districts最多会返回20个数据,若超过限制,请用page请求下一页数据。
        例如page=2;page=3。默认page=1
     4、extensions --控制行政区信息中返回行政区边界坐标点; 可选值:base、all;
        base:不返回行政区边界坐标点;(默认)
        all:只返回当前查询district的边界值,不返回子节点的边界值;目前不能返回乡镇/街道级别的边界值
     5、filter -- 按照指定行政区划进行过滤,填入后则只返回该省/直辖市信息,需填入adcode,为了保证数据的正确,强烈建议填入此参数
     6、callback -- callback值是用户定义的函数名称,此参数只在output=JSON时有效
     7、output --返回数据格式类型,可选值:JSON,XML(默认JSON)


     * @return:返回的是一个promise对象,如果不需要展示组件,只需要获取值,可以直接调用方法,异步获取返回值
       列如:
         const p = this.$refs.provinceForm.provinceList({xxxx(可传值,传值可参考上文params描述) })
         p.then(r => {
           // r 为返回结果
          console.log(r)
         })
     **/
    // 获取省市信息
    provinceList() {
      console.log('??????????????000000000000000')
      var params = {
        keyword: '中国',
        extensions_code: 1
      }
      params.sub_admin = this.subdistrict
      // params.subdistrict = this.subdistrict
      let data = ''
      for (let key in params) {
        data += '&' + key + '=' + params[key]
      }
      // let path = `https://restapi.amap.com/v3/config/district?key=d22348363c34c266f772ae9b635eef2a`
      // let path = 'http://eshield.dev.glsx.com.cn/nesi/apiRegion/search?'
      // path = path + data
      const path = baseConfig.provinceUrl + data
      const pro = fetch(path).then(res => {
        return res.json()
      })
      pro.then(r => {
        this.AllData = JSON.parse(r.data).districts[0].districts
      })
      return pro
    },
    // 省市回显
    init(provinceData) {
      const { province, city, townName, fullAddress, lng, lat } = provinceData
      this.provinceForm.provinceName = province
      this.provinceForm.cityName = city
      this.provinceForm.townName = townName
      this.provinceForm.fullAddress = fullAddress
      this.provinceForm.lng = lng
      this.provinceForm.lat = lat
      if (province) {
        this.AllData.map(item => {
          if (item.name.indexOf(province) != -1) {
            this.provinceForm.provinceName = item.name
            this.cityList = item.districts
            this.provinceForm.provinceCode = item.adcode
            if (city) {
              this.cityList.map(itm => {
                if (itm.name.indexOf(city) != -1) {
                  this.provinceForm.cityCode = itm.adcode
                  this.provinceForm.cityName = itm.name
                  this.townList = itm.districts
                  if (townName) {
                    this.townList.map(itmx => {
                      if (itmx.name.indexOf(townName) != -1) {
                        this.provinceForm.townCode = itmx.adcode
                        this.provinceForm.townName = itmx.name
                      }
                    })
                  }
                }
              })
            }
          }
        })
      }
    },
    selectProvince(val) {
      this.provinceForm.provinceName = val ? val.name : ''
      this.provinceForm.fullAddress = ''
      this.provinceForm.cityName = ''
      this.provinceForm.townName = ''
      if (val) {
        this.cityList = val.districts
      } else {
        val = ''
      }
      // 选择省
      this.$emit('selectProvince', val)
    },

    selectCity(val) {
      this.provinceForm.cityName = val ? val.name : ''
      this.provinceForm.fullAddress = ''
      this.provinceForm.townName = ''
      if (val) {
        this.townList = val.districts
      } else {
        val = ''
      }
      // 选择市
      this.$emit('selectCity', val)
    },

    selectTown(val) {
      this.provinceForm.townName = val ? val.name : ''
      this.provinceForm.fullAddress = ''
      // 选择区
      this.$emit('selectTown', val)
    },

    // 打开地图弹框
    hanleSelectMap() {
      console.log(this.provinceForm)
      this.dialogMapVisible = true
      this.$nextTick(() => {
        // if (this.provinceForm.fullAddress && !this.$refs.mapForm.address) {
          this.$refs.mapForm.address = this.provinceForm.fullAddress
          this.$refs.mapForm.mapInit(this.provinceForm.lng, this.provinceForm.lat)
          // this.$refs.mapForm.addMarker([this.provinceForm.lng, this.provinceForm.lat])
        // }
      })
    },

    // 选择地图地址
    getAddress() {
      if (!this.$refs.mapForm.address) {
        this.$message.success('请选择地址')
        return
      }
      // this.provinceForm.fullAddress = this.$refs.mapForm.address
      // 获取选择经纬度
      let lnglat = this.$refs.mapForm.lnglat
      this.provinceForm.lat = lnglat.lat.toFixed(4)
      this.provinceForm.lng = lnglat.lng.toFixed(4)
      var mapData = this.$refs.mapForm.geocoderAddress
      // 赋值省市区名称和code
      console.log(this.$refs.mapForm, '\\\\\\')
      const { city, city_code, province, district, town_code } = mapData
      if (!this.provinceForm.provinceName) {
        this.provinceForm.provinceName = province
        this.provinceForm.cityName = city
        this.provinceForm.townName = district
        this.provinceForm.provinceCode = mapData.adcode
        this.provinceForm.cityCode = city_code
        this.provinceForm.townCode = town_code
      }
      var fullAddress = ''
      var provincecode = ''
      // 为防止打开地图弹框不选择地址点确定按钮无法正确判断地址选择是否正确产生的报错,设置this.addressData.fullAddress来保存上次选择的地址
      // if (mapData.addressComponent) {
      //   fullAddress = mapData.addressComponent
      //   provincecode = mapData.adcode
      //   this.addressData.fullAddress = fullAddress
      //   this.addressData.provincecode = provincecode
      // } else {
      //   fullAddress = this.addressData.fullAddress
      //   provincecode = this.addressData.provincecode
      // }
      // 获取省市
      var provincename = ''
      var cityname = ''
      var town = ''
      provincename = mapData.province
      cityname = mapData.city ? mapData.city : mapData.district
      town = mapData.district
      // 直辖市需额外判断
      const municipalities = ['北京市', '天津市', '上海市', '重庆市']
      var municipality = municipalities.find(item => item == provincename)
      if (municipality) {
        cityname = cityname.slice(0, 2) + '城区'
        if (municipality === '重庆市') {
          provincecode = provincecode.slice(0, 4)
          provincecode == 5001 ? (cityname = cityname.slice(0, 2) + '城区') : (cityname = cityname.slice(0, 2) + '郊县')
          // 重新赋值城市名
          this.provinceForm.cityName = cityname
        }
      }
      // 判断省市是否匹配
      // 如果只展示省市
      if (this.provinceForm.provinceName && !this.provinceForm.townName) {
        if (this.provinceForm.provinceName !== provincename || this.provinceForm.cityName !== cityname) {
          this.$message.error('您选择的地址错误,请重新选择')
          return
        }
      }
      // 如果展示省市区
      if (this.provinceForm.provinceName && this.provinceForm.townName) {
        if (this.provinceForm.provinceName !== provincename || this.provinceForm.cityName !== cityname || this.provinceForm.townName !== town) {
          this.$message.error('您选择的地址错误,请重新选择')
          return
        }
      }
      this.provinceForm.fullAddress = this.$refs.mapForm.address
      this.dialogMapVisible = false
      // this.subdistrict == 2 ? this.init(province, city) : this.init(province, city, town)
      console.log(this.provinceForm, 'provinceForm')
      // 通过地图选择省市区
      this.$emit('selectAddressByMap', this.provinceForm)
    }
  }
}
</script>

<style scoped lang="scss">
// .province {
//   display: inline-flex;
// }
.select-padding {
  width: 120px !important;
  &:nth-child(1) {
    margin-left: 0;
  }
  margin-left: 10px;
}
.map-input {
  margin-top: 10px;
  ::v-deep .el-input__inner {
    border-right: none;
  }
}
::v-deep {
  .el-input-group__append {
    background-color: #fff;
    padding: 0 11px;
  }
  .el-form-item__content {
    width: 400px !important;
    display: flex;
    margin-left: 0 !important;
  }
  .el-form-item {
    display: flex;
  }
  .el-dialog__body {
    padding: 20px 10px 30px !important;
  }
}
</style>