MerchantList.js 9.47 KB
// components/MerchantList/MerchantList.js
import componentsMixin from '../../mixins/componentsMixin'
import {
  indexApi,
  mineApi
} from '../../api/api'
import mapApi from '../../utils/mapapi'
Component({
  behaviors: [componentsMixin],
  /**
   * 组件的属性列表
   */
  properties: {
    newCars: null,
    routerGoUrl: String,
    isNavigation: Boolean,
    defaultBrand: {
      type: Boolean,
      value: false,
      observer(n, o) {
        if (n) this.getDefaultBrandInfo()
      }
    },
    couponDetailStyle: Boolean
  },

  /**
   * 组件的初始数据
   */
  data: {
    pageNum: 1,
    list: [],
    fromPosition: []
  },
  lifetimes: {
    attached() {
      wx.$util.getViewInfo('.fixed', ({
        height
      }) => {
        this.setData({
          fixedHeight: height
        })
      }, this)
      this.getLocationByIp()
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    getLocationByIp() {
      let {
        defaultBrand
      } = this.data
      mapApi.getLocationByIp().then(({
        city
      }) => {
        if (defaultBrand) return
        let defaultCity = city.replace('市', '')
        this.setData({
          defaultCity,
          cityCode: defaultCity
        })
        this.getGHStoreList()
      }).catch(() => {
        this.getGHStoreList()
      })
    },
    phoneCall(e) {
      let {
        phone
      } = e.currentTarget.dataset
      if (!phone) return
      wx.$util.phoneCall(phone)
    },
    search(e) {
      let storeName = e.detail
      this.setData({
        storeName
      })
      this.clearData()
    },
    choose(e) {
      this.setData(e.detail)
      this.clearData()
    },
    chooseStore(e) {
      let {
        item
      } = e.currentTarget.dataset
      // 新车频道选择门店不返回,直接进入下一个页面
      if (this.data.newCars) {
        let temp = JSON.stringify(item)
        wx.navigateTo({
          url: '/packageIndex/pages/newCars/index/index?store=' + temp
        })
        return
      }
      if (this.data.routerGoUrl) {
        wx.$router.go(this.data.routerGoUrl, {
          storeInfo: item
        })
        return
      }
      wx.$router.back(page => {
        page.setData({
          store: item,
          'obj.storeCode': item.storeCode
        })
      })
    },
    getGHStoreList() {
      let {
        list,
        pageNum,
        storeName,
        brandId,
        cityCode,
        nothing,
        defaultFlag
      } = this.data
      let params = {
        pageNum
      }
      if (storeName) params.storeName = storeName
      if (brandId) params.brandId = brandId
      if (cityCode) params.cityCode = cityCode
      let storeCode = wx.$util.getStorageSync('srcm_shopmall_store_code')
      wx.$util.showLoading('加载中...')
      indexApi.getGHStoreList(params).then(data => {
        wx.hideLoading()
        if (data.length == 0) nothing = true
        data.map(e => {
          if (e.storeCode == storeCode) e.current = true
        })
        this.setData({
          list: [...list, ...data],
          listFlag: true,
          nothing
        })
        this.setCalculateDistance()
        if (storeCode && !defaultFlag) {
          this.setDefaultStore(storeCode)
        }
      })
    },
    setDefaultStore(storeCode) {
      indexApi.getGHStoreList({
        storeCode
      }).then(data => {
        if (data.length) {
          let [defaultStore] = data
          this.setData({
            defaultStore,
            defaultFlag: true
          })
          setTimeout(() => {
            this.getDefaultDistance()
          }, 1000)
        }
      })
    },
    getDefaultDistance() {
      let {
        fromPosition,
        defaultStore
      } = this.data
      if (fromPosition.length && defaultStore && !defaultStore.distance) {
        let {
          location
        } = defaultStore
        mapApi.calculateDistance(fromPosition, [location.latitude, location.longitude]).then(data => {
          let {
            distance
          } = data.elements[0]
          this.setData({
            'defaultStore.distance': Number((distance / 1000)).toFixed(2)
          })
        })
      }
    },
    setCalculateDistance() {
      let {
        list,
        fromPosition
      } = this.data
      if (!list.length || !fromPosition.length) return
      let toList = []
      let indexList = []
      let toGroup = []
      let indexGroup = []
      list.map((e, index) => {
        let {
          location
        } = e
        if (location && location.latitude) {
          if (!e.distance && location.latitude != '0.0') {
            let latitude = Number(location.latitude),
              longitude = Number(location.longitude)
            latitude = latitude > 90 ? Number(location.longitude) : Number(location.latitude)
            longitude = latitude > 90 ? Number(location.latitude) : Number(location.longitude)
            toList.push([latitude, longitude])
            indexList.push(index)
            if (toList.length >= 10) {
              toGroup.push(toList)
              indexGroup.push(indexList)
              toList = []
              indexList = []
            }
          }
        }
      })
      if (toList.length) {
        toGroup.push(toList)
        indexGroup.push(indexList)
      }
      if (toGroup.length) {
        let index = 0
        let interval = setInterval(() => {
          if (index == toGroup.length - 1) clearInterval(interval)
          mapApi.calculateDistanceMatrix(fromPosition, toGroup[index]).then(({
            rows: [data]
          }) => {
            let distanceList = []
            data.elements.map(e => {
              let distance = Number((e.distance / 1000)).toFixed(2)
              distanceList.push(distance)
            })
            indexGroup[index].map((s, ind) => {
              if (!list[s].distance) {
                this.setData({
                  [`list[${s}].distance`]: distanceList[ind]
                })
              }
            })
            index += 1
          })
        }, 1 / 4 * 1000)
      }

    },

    openLocation(e) {
      let {
        item
      } = e.currentTarget.dataset
      if (!item.distance) {
        mapApi.geocoder(item.address).then(({geocodes})=> {
          let location = geocodes[0].location.split(',')
          wx.openLocation({
            longitude: Number(location[0]),
            latitude: Number(location[1]),
            name: item.storeName,
            address: item.address
          })
        })
        return
      }
      wx.openLocation({
        latitude: Number(item.location.latitude),
        longitude: Number(item.location.longitude),
        name: item.storeName,
        address: item.address
      })
    },
    clearData() {
      this.setData({
        listFlag: false,
        list: [],
        nothing: false,
        pageNum: 1
      })
      this.getGHStoreList()
    },
    searchAll() {
      let {
        defaultBrand,
        brandName,
        brandId
      } = this.data
      this.setData({
        storeName: '',
        cityCode: '',
        brandName: defaultBrand ? brandName : '',
        brandId: defaultBrand ? brandId : ''
      })
      this.clearData()
    },
    showIndexList(e) {
      let {
        type
      } = e.currentTarget.dataset
      let {
        defaultBrand
      } = this.data
      if (defaultBrand && type != 0) return
      this.setData({
        [type == 0 ? 'showCity' : 'showBrand']: true
      })
    },
    // 下拉触底
    scrollTolower(e) {
      let {
        pageNum,
        nothing
      } = this.data
      if (nothing) return
      this.setData({
        pageNum: ++pageNum
      })
      this.getGHStoreList()
    },
    /**打开授权设置 */
    authAddress() {
      this.setData({
        showAuth: true
      })
    },
    /**授权位置成功 */
    authSuccess() {
      this.setData({
        flag: true,
        unauthorized: false
      })
      this.getLocation()
    },
    /**授权失败 */
    authFail() {
      this.setData({
        unauthorized: true,
        flag: true
      })
    },
    /**获取当前位置 */
    getLocation() {
      let {
        fromPosition
      } = this.data
      if (fromPosition.length) return
      wx.$Track.getAddressInfo().then(({
        location
      }) => {
        this.setData({
          fromPosition: [location.lat, location.lng],
          unauthorized: false
        })
        this.setCalculateDistance()
        this.getDefaultDistance()
      })
    },
    getDefaultBrandInfo() {
      let brandList = wx.$util.getStorageSync('srcm_shopmall_brand_list')
      mineApi.getGHUserCarList().then(({
        code,
        data
      }) => {
        if (code == '0') {
          let {
            vehs
          } = data
          if (vehs.length) {
            let {
              brandName
            } = vehs[0]
            if (brandList) {
              this.setBrandId(brandList, brandName)
            } else {
              indexApi.getBrandList().then(res => {
                wx.$util.setStorageSync('srcm_shopmall_brand_list', res.data)
                this.setBrandId(res.data, brandName)
              })
            }
          } else {
            this.setData({
              defaultBrand: false
            })
            this.clearData()
          }
        }
      })
    },
    setBrandId(data, brandName) {
      Object.keys(data).map(letter => {
        data[letter].map(s => {
          if (s.brandName == brandName) {
            this.setData({
              brandId: s.brandId,
              brandName
            })
            this.clearData()
          }
        })
      })
    }
  }
})